package com.march.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.march.common.CustomException;
import com.march.dto.SetmealDto;
import com.march.entry.Setmeal;
import com.march.entry.SetmealDish;
import com.march.mapper.SetmealMapper;
import com.march.service.SetmealDishService;
import com.march.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /*
    * 新增套餐
    * */
    @Override
    @Transactional
    public void savaWithDish(SetmealDto setmealDto) {

        //套餐基本信息的保存
        this.save(setmealDto);


        //套餐内菜品信息的套餐id设置进入
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes().stream().map(item -> {
            SetmealDish setmealDish = new SetmealDish();
            BeanUtils.copyProperties(item,setmealDish);

            setmealDish.setSetmealId(setmealDto.getId());

            return setmealDish;
        }).collect(Collectors.toList());

//        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
//        setmealDishes.stream().map(item->{
//            item.setSetmealId(setmealDto.getId());
//            return item;
//        }).collect(Collectors.toList());

        //套餐内菜品信息保存
        setmealDishService.saveBatch(setmealDishList);
    }

    /*
    * 删除套餐
    * */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {

        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId,ids);
        lqw.eq(Setmeal::getStatus,1);
        long count = this.count(lqw);
        if(count > 0){
            throw new CustomException("套餐正在售卖中...");
        }
        //查询套餐状态
        this.removeByIds(ids);

        //删除相关表数据
        LambdaQueryWrapper<SetmealDish> lqw1 = new LambdaQueryWrapper<>();
        lqw1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lqw1);
    }
}
